package com.jp.fm.servlet;

import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.easymock.EasyMock;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.jp.fm.EasyMockParent;
import com.jp.fm.dao.AccountDao;
import com.jp.fm.dao.CategoryDao;
import com.jp.fm.data.Account;
import com.jp.fm.data.Account.AccountBalance;
import com.jp.fm.service.CategoryService;

public class RefreshAccountTest extends EasyMockParent {

	private RefreshAccount servlet = null;

	private HttpServletRequest mockRequest = null;
	private HttpServletResponse mockResponse = null;
	private AccountDao mockAccountDao = null;
	private CategoryDao mockCategoryDao = null;
	private CategoryService mockCategoryService = null;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
		super.setUp();

		servlet = new RefreshAccount();
	}

	@After
	public void tearDown() throws Exception {
		super.tearDown();
	}

	@Test
	public final void testDoPost() throws ServletException, IOException {

		Account account = new Account(null, "test1", null, null, null,
				new AccountBalance(null, Float.valueOf("5000"), null), 0);
		account.setLastupdate(new Timestamp(new Date().getTime()));

		Class[] args = { HttpServletRequest.class, HttpServletResponse.class };

		RefreshAccount partialMockServlet = (RefreshAccount) createPartialMock(
				RefreshAccount.class, "doPost", args, false);

		PrintWriter mockPrintWriter = EasyMock
				.createNiceMock(PrintWriter.class);

		partialMockServlet.setAccountDao(mockAccountDao);
		partialMockServlet.setCategoryDao(mockCategoryDao);
		partialMockServlet.setCategoryService(mockCategoryService);

		expect(mockRequest.getParameter("acct")).andReturn("test1");
		expect(mockAccountDao.findByName("test1")).andReturn(account).times(2);
		mockResponse.setContentType("application/json");
		expectLastCall();
		expect(mockResponse.getWriter()).andReturn(mockPrintWriter);

		replayMocks();
		EasyMock.replay(mockPrintWriter);
		EasyMock.replay(partialMockServlet);

		partialMockServlet.doPost(mockRequest, mockResponse);

		EasyMock.verify(mockPrintWriter);
		EasyMock.verify(partialMockServlet);
	}
}
